package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 文章实时导入到ES的监听器
 */
@Slf4j
@Component
public class ImportArticleToESListener {

    @Autowired
    private RestHighLevelClient client;

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void msg(ConsumerRecord<String,String> consumerRecord){

        if(consumerRecord!=null){
            try {
                //1. 获取value的文章json
                String searchArticleVoJSON = consumerRecord.value();

                //2. 将json转为SearchArticleVo对象
                SearchArticleVo searchArticleVo = JSON.parseObject(searchArticleVoJSON, SearchArticleVo.class);

                //3. 构建IndexRequest设置文章JSON数据指定文档ID
                IndexRequest indexRequest = new IndexRequest("app_info_article");
                indexRequest.source(searchArticleVoJSON, XContentType.JSON).id(String.valueOf(searchArticleVo.getId()));

                //4. 调用client的index方法将文章导入到ES
                IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

                //5. 输出响应结果
                String result = indexResponse.getResult().getLowercase();//如果结果是created则表示导入成功

                boolean flag = "created".equals(result) ? true : false;
                log.info("[文章实时导入ES]导入结果：{},文章ID：{}", flag, searchArticleVo.getId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
